import router from './router'
import store from './store'
import { Message, Loading } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css'// progress bar style
import { getToken } from '@/utils/auth' // getToken from cookie
NProgress.configure({ showSpinner: false })// NProgress Configuration
let loadingInstance = ''; let timer = null; const timeDiff = 500
// permission judge function
function hasPermission(roles, permissionRoles) {
  if (roles.indexOf('admin') >= 0) return true // admin permission passed directly
  if (!permissionRoles) return true
  return roles.some(role => permissionRoles.indexOf(role) >= 0)
}

/**
 * 设置浏览器头部标题
 */
const setTitle = (title) => {
  title = title ? `${title}` : ''
  window.document.title = title
}
const whiteList = ['/login', '/autoLogin', '/auth-redirect', '/emailPass', '/tool', '/tool/form']
router.beforeEach(async(to, from, next) => {
  if (from.meta.noCache === false) {
    store.dispatch('addCachedView', from)
  }
  NProgress.start() // start progress bar
  if (timer) {
    clearTimeout(timer)
    timer = null
  }
  timer = setTimeout(() => {
    loadingInstance = Loading.service({ spinner: 'el-icon-loading', text: '数据加载中' })
  }, timeDiff)
  if (store.state.app['axiosPromiseCancel'].length > 0) {
    store.state.app['axiosPromiseCancel'].forEach(e => {
      if (e && e.f) {
        e.f()
      }
    })
  }
  store.state.app['axiosPromiseCancel'] = []
  if (store.getters.permission_locationRouter.length === 0) {
    await store.dispatch('GetLocationRouter')
  }
  // next()
  if (getToken()) { // determine if there has token
    /* has token*/
    if (!store.getters.browserHeaderTitle) {
      store.dispatch('GetTitle')
    }
    if (!sessionStorage.getItem('FILE_SAVE_THIRD_CONFIG')) {
      store.dispatch('GetSysConfig')
    }
    if (to.path === '/login') {
      next({ path: '/' })
      NProgress.done() // if current page is dashboard will not trigger	afterEach hook, so manually handle it
      if (loadingInstance) {
        setTimeout(() => {
          loadingInstance.close()
        }, 100)
      }
      clearTimeout(timer)
      timer = null
    } else {
      // 当前为登录页面不调用获取用户信息接口，防止页面提示error
      if (localStorage.getItem('isLogin') == 0) {
        store.dispatch('FedLogOut').then(() => {
          next({ path: '/' })
        })
      } else {
        if (store.getters.roles.length === 0) { // 判断当前用户是否已拉取完user_info信息
          store.dispatch('GetUserInfo').then(res => { // 拉取user_info
            const roles = res.data.data.menuDatas // note: roles must be a array! such as: ['editor','develop']
            const btnRoles = (res.data.data.buttonDatas && res.data.data.buttonDatas.length > 0) ? res.data.data.buttonDatas.join(',') : ''
            store.dispatch('GenerateButtons', btnRoles)
            store.dispatch('GenerateRoutes', roles).then((routers) => { // 根据roles权限生成可访问的路由表
              router.addRoutes(routers) // 动态添加可访问路由表
              next({ ...to, replace: true }) // hack方法 确保addRoutes已完成 ,set the replace: true so the navigation will not leave a history record
            })
          }).catch((err) => {
            store.dispatch('FedLogOut').then(() => {
              err && Message.error(err)
              next({ path: '/' })
            })
          })
        } else {
          // 没有动态改变权限的需求可直接next() 删除下方权限判断 ↓
          if (hasPermission(store.getters.roles, to.meta.roles)) {
            next()
          } else {
            next({ path: '/401', replace: true, query: { noGoBack: true }})
          }
          // 可删 ↑
        }
      }
    }
  } else {
    /* has no token*/
    if (whiteList.indexOf(to.path) !== -1) { // 在免登录白名单，直接进入
      if (loadingInstance) {
        setTimeout(() => {
          loadingInstance.close()
        }, 100)
      }
      clearTimeout(timer)
      timer = null
      next()
    } else {
      next(`/login?redirect=${to.path}`) // 否则全部重定向到登录页
      NProgress.done() // if current page is login will not trigger afterEach hook, so manually handle it
      if (loadingInstance) {
        setTimeout(() => {
          loadingInstance.close()
        }, 100)
      }
      clearTimeout(timer)
      timer = null
    }
  }
})

router.afterEach(() => {
  NProgress.done() // finish progress bar
  setTimeout(() => {
    if (loadingInstance) {
      loadingInstance.close()
    }
    clearTimeout(timer)
    timer = null
  }, 10)
  setTimeout(() => {
    const browserHeaderTitle = store.getters.browserHeaderTitle
    setTitle(browserHeaderTitle)
  }, 0)
})
